/**
 * Created with JetBrains WebStorm. User: Administrator Date: 13-11-11 Time: 上午11:18 To change this template use File |
 * Settings | File Templates.
 */
Ext.define("byb.workspace", function() {
    var loginWindow, viewport;
    return {
        init: function() {
            var result = this.isLogin();

            if (true === result.login){
               loginWindow = {};
               loginWindow.destroy = function(){};
               this.onLoginSuccess(null, result);
            }else {
               loginWindow = this.buildLoginWindow();
            }
        },
        buildLoginWindow: function() {
            loginWindow = Ext.create("byb.view.window.UserLoginWindow", {
                scope: this,
                handler: this.onLogin
            });
            return loginWindow;
        },
        isLogin: function() {
        	var data = {"login": false};

        	Ext.Ajax.request({
        	    url: byb.Constant.APIRoot+'/user/getLoginInfo',
        	    async: false,
        	    sync: true,
        	    success: function(response){
        	    	var text = Ext.decode(response.responseText);
        	        if(text && text.success && text.results && "true" === String(text.success)){
        	            data.login = true;
        	            data.response = response;
        	            byb.controller.SystemController.loginUserOrgCode = text.results.orgCode;
        	        }else {
        	        	data.login = false;
        	        }
        	    },
        	    failure : function() {  
        	    	data.login = false;
                }
        	});
        	return data;
        },
        onLogin: function() {
        	 var result = this.isLogin();

             if (true === result.login){//如果已经登录
            	 window.location = document.URL;
             }else {//如果没有login
            	 var form = loginWindow.down("form");
                 if (form.getForm().isValid()) {
                     Ext.getBody().el.mask('登录中...', 'x-mask-loading');
                     form.getForm().submit({
                         url: byb.Constant.LoginURL,
                         params:{"login":true},
                         success: this.onLoginSuccess,
                         failure: this.onLoginFailure,
                         scope: this
                     });
                 }
             }
             
            
        },
        onLoginSuccess: function(form, action) {
        	var responseText = action.response.responseText;
        	var result = Ext.decode(responseText);
        	if("true" === String(result.success)){
            	this.updateLoginInfo();
                // var data = action.result.results;
                // Ext.util.Cookies.set("loginCookie",Ext.encode(data));
                this.buildViewport();
                //创建菜单树 
                var me = Ext.ComponentQuery.query('AccordionView')[0];
                Ext.Ajax.request({
                    url: byb.Constant.APIRoot+"/menu/getMenuByUserId",
                    method: 'GET',
                    success: function(response, opts) {
                        var obj = Ext.decode(response.responseText);
                        if(obj){
                            for(m in obj){
                               if(obj[m][0]){
                                   me.add(me.createItem(obj[m][0].name,obj[m][0].icon, obj[m][1]));
                               } 
                            }
                        }
                    }
                });
                
                if(loginWindow){
                	loginWindow.destroy();
                }
                loginWindow = null;
        	}else{
            	 Ext.getDom('randcodeImg').src=byb.Constant.RandCodeURL+'?'+(new Date().getTime());
                 Ext.MessageBox.alert("登录失败", "用户名或密码错误!");
        	}
        	
        	Ext.getBody().el.unmask();
            /***********************************************************************************************************
             * var cookie = Ext.util.Cookies.get("loginCookie"); if (cookie) { this.buildViewport();
             * loginWindow.destroy(); loginWindow = null; }else { this.onLoginFailure(); }
             **********************************************************************************************************/
        },
        onLoginFailure: function(form, action) {
        	Ext.getDom('randcodeImg').src=byb.Constant.RandCodeURL+'?'+(new Date().getTime());
        	Ext.MessageBox.alert("登录失败", "验证码不正确!");
        	Ext.getBody().el.unmask();
        },

        onAfterLogout: function() {
            this.destroy();
        },
        buildViewport: function() {
            viewport = Ext.create("byb.view.Viewport");
            Ext.getBody().unmask();
        },
        onAfterAjaxReq: function(options, success, result) {
            Ext.getBody().unmask();
            if (success === true) {
                var jsonData;
                try {
                    jsonData = Ext.decode(result.responseText);
                } catch (e) {
                    Ext.MessageBox.alert('Error!', 'Data returned is not valid!');
                }
                options.succCallback.call(options.scope, jsonData, options);

            } else {
                Ext.MessageBox.alert('Error!', 'The web transaction failed!');
            }
        },
        destroy: function() {
            viewport.destroy();
            viewport = null
            this.init();
        }
        ,updateLoginInfo:function(){
        	Ext.Ajax.request({
        	    url: byb.Constant.APIRoot+'/user/getLoginInfo',
        	    success: function(response){
        	    	var text = null;
        	    	if(response.responseText.length > 0){
        	    		text = Ext.decode(response.responseText);
                        var data = text.results;
                        Ext.util.Cookies.set("loginCookie",Ext.encode(data));
        	    	}
        	        if(text && text.success && text.results){
        	            byb.controller.SystemController.loginUserOrgCode = text.results.orgCode;
        	        	var user = text.results.fullname ? text.results.fullname : text.results.username;
        	        	var isDepartment = text.results.department;
        	        	var isGroup= text.results.group;
            	        var topView =  Ext.ComponentQuery.query('TopView')[0];
                        var loginInfoView =  Ext.ComponentQuery.query('TopView [name=loginfo]')[0];
                        var companyView =  Ext.ComponentQuery.query('TopView [name=companyId]')[0];
                        var orgDescView =  Ext.ComponentQuery.query('TopView [name=orgDesc]')[0];

                        var welcome = '你好, ' + user;
                        var loginHtml = 
    	                	 welcome
    	                	+ "<a href='#' onclick='javascript:byb.controller.SystemController.onModifyPassword(); return false;' style='margin-left:20px;color:#66ff00'>修改密码</a>" 
    	                	+ "<a href='"+byb.Constant.LogoutURL+"' style='margin-left:20px;color:#66ff00'>退出系统</a>";
                            //+ "<a href='#' onclick='javascript:byb.controller.SystemController.showMessageIn(); return false;' style='margin-left:20px;color:#66ff00'>修改密码</a>" 
                            //+ "<a href='#' onclick='javascript:byb.controller.SystemController.showMessageOut(); return false;' style='margin-left:20px;color:#66ff00'>退出系统</a>";
                        var orgDesc = '您属于 :&nbsp;&nbsp;' + text.results.orgName;
                        
                        if(isGroup){ 
                        	orgDescView.hide();
                            companyView.show();
                        }else{                    
                            orgDescView.getEl().el.dom.innerHTML = orgDesc;
                        	orgDescView.show();
                            companyView.hide();   
                        }
                        
                        loginInfoView.getEl().el.dom.innerHTML = loginHtml;
        	        }
        	    }
        	});
        }
        
    };
});
